import {connect} from "react-redux";
import React, {useState, useEffect} from "react";
import {Button, Col, Form, Input, message, Row, Select, Upload} from "antd";
import {get, post} from "../../../utils";
import {config, mUrl} from "../../../config";
import mUtils from "../../../utils/utils";
import {PlusOutlined} from "@ant-design/icons";

const Page = () => {
    const [form] = Form.useForm();
    const [orgstate, setOrgstate] = useState(undefined);
    const [mainImgFileList, setMainImgFileList] = useState([]); // 主图
    const [businessFileList, setBusinessFileList] = useState([]); // 营业执照
    const [options, setOptions] = useState([]); // 分类列表
    
    useEffect(() => {
        searchTypeList();
    }, []);

    const searchTypeList = () => {
        get(mUrl.searchAllClassify, {}).then((res) => {
            const data = res.data.map((item) => {
                return {
                    value: item.classifyid,
                    label: item.name,
                };
            });
            setOptions(data);
        });
    };

    const selectImg = ({fileList}, id) => {
        if (id === 1) { // 选择主图
            setMainImgFileList(fileList);
        } if (id === 5) { // 选择视频
            setBusinessFileList(fileList);
        }
    };
    // 预览图片
    const handlePreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };

    const uploadButton = ( // 选择图片按钮
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>请选择</div>
        </div>
    );

    const submit = (type) => {
        setOrgstate(type);
        setTimeout(() => {
            form.submit();
        }, 200);
    };
    
    const onFinish = async (value) => {
        if (mainImgFileList.length) {
            value.imageurl = mUtils.setImageUrl(mainImgFileList);
        }
        if (businessFileList.length) {
            value.businessurl = mUtils.setImageUrl(businessFileList);
        }
        if (value.classification) {
            const orgClassifyList = [];
            value.classification.forEach((item) => {
                orgClassifyList.push({classifyid: item});
            });
            value.orgClassifyList = orgClassifyList;
            delete value.classification;
        }
        value.orgtype = 2;
        value.orgstate = orgstate + '';
        let url = mUrl.addOrganization;
        const res = await post(url, value);
        if (res.state === 1) {
            message.success('添加成功');
            window.closeWin();
            window.onSelectWin({title: '经销商列表', path: '/main/distributor', page: '/main/distributor'});
        }
    };

    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>经销商管理 / 添加经销商</p></label>
            <Row>
                <Col span={12}>
                    <Form form={form} onFinish={onFinish}>
                        <Form.Item name={"appletslogin"}
                                   label={'小程序账号'}
                                   rules={[{required: true, message: '请输入'}]}
                                   labelCol={{span: 5}}
                                   style={{marginBottom: 15}}>
                            <Input allowClear style={{width: 200}} placeholder={'请输入'}/>
                        </Form.Item>
                        <Form.Item name={"orgname"}
                                   label={'工厂名称'}
                                   rules={[{required: true, message: '请输入'}]}
                                   labelCol={{span: 5}}
                                   style={{marginBottom: 15}}>
                            <Input allowClear style={{width: 200}} placeholder={'请输入'}/>
                        </Form.Item>
                        <Form.Item name={"linkman"}
                                   label={'联系人'}
                                   labelCol={{span: 5}}
                                   style={{marginBottom: 15}}>
                            <Input allowClear style={{width: 200}} placeholder={'请输入'}/>
                        </Form.Item>
                        <Form.Item
                            label='分类'
                            name='classification'
                            // rules={[{required: true, message: '请选择分类'}]}
                            labelCol={{span: 5}}
                        >
                            <Select
                                mode="multiple"
                                style={{width: 200}}
                                placeholder="请选择"
                            >
                                {
                                    options.map((item) => {
                                        return (
                                            <Select.Option key={item.value}>{item.label}</Select.Option>
                                        );
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item name={"linkphone"}
                                   label={'联系方式'}
                                   labelCol={{span: 5}}
                                   style={{marginBottom: 15}}>
                            <Input allowClear style={{width: 200}} placeholder={'请输入'}/>
                        </Form.Item>
                        <Form.Item
                            label='图片'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                listType="picture-card"
                                fileList={mainImgFileList}
                                onPreview={handlePreview}
                                accept=".jpeg,.jpg,.png"
                                onChange={(file) => {
                                    selectImg(file, 1);
                                }}
                            >
                                {mainImgFileList.length >= 5 ? null : uploadButton}
                            </Upload>
                            <span style={{color: 'red'}}>最多可上传5个，建议尺寸：500*250px</span>
                        </Form.Item>
                        <Form.Item
                            label='营业执照'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                listType="picture-card"
                                fileList={businessFileList}
                                onPreview={handlePreview}
                                accept=".jpeg,.jpg,.png"
                                onChange={(file) => {
                                    selectImg(file, 5);
                                }}
                            >
                                {businessFileList.length >= 2 ? null : uploadButton}
                            </Upload>
                            <span style={{color: 'red'}}>最多可上传2个，建议尺寸：500*250px</span>
                        </Form.Item>
                        <Form.Item name={"remark"}
                                   label={'简介'}
                                   labelCol={{span: 5}}
                                   style={{marginBottom: 15}}>
                            <Input.TextArea allowClear rows={5} placeholder={'请输入'}/>
                        </Form.Item>
                        <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                            <Button style={{marginRight: 15}}
                                    onClick={() => submit(0)}
                                    type={'primary'}
                            >提交成为待认证经销商</Button>
                            {
                                businessFileList.length > 0 &&
                                <Button
                                    style={{marginRight: 15}}
                                    onClick={() => submit(1)}
                                    type={'primary'}
                                >提交并审核通过</Button>
                            }
                            <Button
                                onClick={_ => {
                                    window.closeWin();
                                    window.onSelectWin({title: '经销商列表', path: '/main/distributor', page: '/main/distributor'});
                                }}
                            >取消</Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
        </div>
    );
};

export default connect()(Page);